import NetAdapter from "../../adpapter/NetAdapter";
import { AlertManager, AlertType } from "../../alert/AlertManager";
import { CallID } from "../../CallID";
import { Common_UIPath } from "../../common/Common_Define";
import { GameWorld } from "../../component/GameWorld";
import ItemScrollCom from "../../component/itemscroll/ItemScrollCom";
import { MainRole } from "../../component/MainRole";
import { MainRoleClone } from "../../component/MainRoleClone";
import { Cfg } from "../../config/Cfg";
import { Const } from "../../config/Const";
import { MVC } from "../../framework/MVC";
import { Notifier } from "../../framework/Notifier";
import { Time } from "../../framework/Time";
import { UIManager } from "../../framework/UIManager";
import GlobalData from "../../GlobalData";
import { ListenID } from "../../ListenID";
import { BulletManager } from "../../manager/BulletManager";
import { GameVoManager } from "../../manager/GameVoManager";
import { Manager } from "../../manager/Manager";
import { RoleManager } from "../../manager/RoleManager";
import { Util } from "../../utils/Util";
// import { RoleManager } from "../../manager/RoleManager";
import { FightDamageDisplay } from "../fight/FightDamageDisplay";
import FightModel from "../fight/FightModel";
import { DecorateItem } from "../fight/item/DecorateItem";
import { GameCamera } from "../fight/item/GameCamera";

const { ccclass, property } = cc._decorator;

@ccclass
export default class TiaozhanScene extends cc.Component {

    @property(cc.Node)
    rewardPanel: cc.Node = null;

    @property(cc.Label)
    coinLabel: cc.Label = null;

    @property(cc.Label)
    battleLabel: cc.Label = null;

    private gamePanel: cc.Node = null;
    private bulletPanel: cc.Node = null;
    private toolPanel: cc.Node = null;
    private mainRole: cc.Node = null;
    private enemyRole: cc.Node = null;
    private startBtn: cc.Node = null;
    private roleCamera: cc.Camera = null;

    private gameCamera: GameCamera;
    private handShankBg: cc.Node = null;
    private handShank: cc.Node = null;
    private effectPanel: cc.Node = null;
    private hitPosNode: cc.Node = null;
    private reliveBoom: cc.Node = null;
    private gameState: number = 0;
    private hurtPanel: cc.Node = null;
    private warn: cc.Node = null;
    private levelWarn: cc.Node = null;
    private bglist: cc.Node = null;
    private decorateItem: cc.Node = null;
    private decorateMg: DecorateItem = null;
    public dropPanel;
    private realSize: cc.Size;
    private battleWall: cc.Animation;

    private coin = 0;
    private battle = 0;

    private roles = {
        self: new MainRoleClone(),
        enemy: new MainRoleClone()
    };

    onLoad() {
        RoleManager.getInstance.isNeedUpate = false;
    }

    start() {
        this.initScene();

        this.bglist.active = true;
        this.decorateItem && (this.decorateItem.active = true);

        Manager.audio.playMusic(508, true);
        cc.director.getCollisionManager().enabled = true;

        this.startGame();
    }

    initScene() {
        this.gamePanel = this.node.getChildByName("gamePanel");
        this.gamePanel.active = true;
        this.bulletPanel = this.node.getChildByName("bulletPanel");
        this.toolPanel = this.node.getChildByName("toolPanel");
        this.effectPanel = this.node.getChildByName("effectPanel");
        this.hurtPanel = this.node.getChildByName("hurtNumPanel");
        this.warn = this.node.getChildByName("warn");
        this.levelWarn = this.node.getChildByName("warn2");
        let battlepanel = this.node.getChildByName("battlePanel");
        this.battleWall = battlepanel.children[0].getComponent(cc.Animation);
        this.battleWall.node.active = false;
        let size: cc.Size = Notifier.call(CallID.Setting_GetRealDesignSize);
        this.realSize = size;
        this.warn.height = size.height - 5; this.warn.width = size.width - 5;
        this.warn.active = false;
        this.levelWarn.height = size.height - 5; this.levelWarn.width = size.width - 5;
        this.levelWarn.active = false;
        this.mainRole = this.gamePanel.getChildByName("player");
        this.enemyRole = this.gamePanel.getChildByName("enemy");
        this.roleCamera = this.node.getChildByName("Main Camera").getComponent(cc.Camera);
        this.handShankBg = cc.find("control/bg", this.node);
        this.handShank = this.handShankBg.getChildByName("circle");
        this.reliveBoom = this.node.getChildByName("reliveBoom");
        this.reliveBoom.scale = 0;
        this.reliveBoom.active = false;
        let footmark = this.gamePanel.getChildByName("footdecorate");
        let footmarkParent = this.gamePanel.getChildByName("footMark");
        this.bglist = this.node.getChildByName("bglist");
        this.decorateItem = this.node.getChildByName("decorate");
        Manager.map.changeMapByChapterId(6, this.bglist, this.decorateItem);
        this.handShankBg.active = false;
        // this.handShankBg.parent.active = true;
        this.gameCamera = new GameCamera(this.roleCamera, this.mainRole);
        FightModel.getInstance.bulletParent = this.bulletPanel;
        FightModel.getInstance.bulletMonParent = this.node.getChildByName("bulletMonPanel");
        FightModel.getInstance.warnParent = this.node.getChildByName("warnPanel");
        FightModel.getInstance.specialEffectNode = this.effectPanel.getChildByName("specialHit");
        this.dropPanel = this.node.getChildByName("dropPanel");
        FightModel.getInstance.footMarkNode = footmark;
        FightModel.getInstance.footmarkParent = footmarkParent;
        FightModel.getInstance.bombParent = this.node.getChildByName("bombPanel");
        FightModel.getInstance.gamePanel = this.gamePanel;
        GameVoManager.getInstance.myUserVo.curLogLevel = GameVoManager.getInstance.myUserVo.top_level;
        GameVoManager.getInstance.stateVo.curLevel = GameVoManager.getInstance.myUserVo.top_level + 1;
        // this.registerTouchOperate();
    }

    /**注册触摸事件 */
    private registerTouchOperate() {
        this.gamePanel.on(cc.Node.EventType.TOUCH_START, this.onTouchStart, this);
        this.gamePanel.on(cc.Node.EventType.TOUCH_MOVE, this.onTouchMove, this);
        this.gamePanel.on(cc.Node.EventType.TOUCH_END, this.onTouchEnd, this);
        // this.gamePanel.on(cc.Node.EventType.TOUCH_CANCEL, this.onTouchEnd, this);
    }

    public onRoleMove() {
        this.roles.self.onMove(this.shootPos);
    }

    private shootPos: cc.Vec2 = cc.Vec2.ZERO;
    private startPos: cc.Vec2 = cc.Vec2.ZERO;
    private touchCount: number = 0;
    private catchRocker: boolean = false;
    public onTouchStart(event: cc.Event.EventTouch) {
        if (this.gameState != 1 || FightModel.getInstance.isPause > 0) return;
        // if (this.touchCount == 0) {
        let delta = this.handShankBg.parent.convertToNodeSpaceAR(event.getLocation());
        this.handShankBg.active = true;
        // if (this.handShankBg.position.sub(delta).mag() <= Const.OperateDis) {
        this.catchRocker = true;
        this.schedule(this.onRoleMove, 0.02);
        // this.setRockerPos(delta);
        this.startPos = delta;
        this.handShankBg.position = delta;
        // }
        // //console.log(delta, this.handShankBg.position.sub(delta).mag());
        // }
        this.touchCount++;
    }
    public onTouchMove(event: cc.Event.EventTouch) {
        if (this.gameState != 1 || FightModel.getInstance.isPause > 0) return;
        if (this.catchRocker) {
            let delta = this.handShankBg.parent.convertToNodeSpaceAR(event.getLocation());
            this.setRockerPos(delta);
        }
    }

    public onTouchEnd(event: cc.Event.EventTouch) {
        if (this.gameState != 1 || FightModel.getInstance.isPause > 0) return;
        this.touchCount--;
        if (this.touchCount <= 0) {
            this.touchCount = 0;
            this.resetRocker();
            Notifier.send(ListenID.Fight_RoleStand);
            // this.handShankBg.active = false;
        }
    }


    /**设置摇杆坐标，适配屏幕 */
    public setRockerInfo() {
        let size: cc.Size = Notifier.call(CallID.Setting_GetRealDesignSize);
        this.handShankBg.position = cc.v2(0, -0.5 * size.height + 250);
    };

    public setRockerPos(delta: cc.Vec2) {
        let pos = delta.sub(this.startPos);
        this.handShankBg.position = delta;//pos;
        this.shootPos = pos.normalize();
        let len = pos.mag();
        let shankPos = cc.Vec2.ZERO.sub(this.shootPos.mul(cc.misc.clampf(pos.mag(), 0, 88)));
        this.handShank.position = shankPos;
        if (len >= 88) {
            let bgpos = delta.sub(this.shootPos.mul(88));
            this.startPos = bgpos;
        }
    }
    /**重置摇杆 */
    public resetRocker() {
        this.handShank.position = cc.Vec2.ZERO;
        this.unschedule(this.onRoleMove);
        this.shootPos = cc.Vec2.ZERO;
        this.startPos = cc.Vec2.ZERO;
        this.catchRocker = false;
        this.handShankBg.x = 0;
        this.handShankBg.y = -500;
    }

    public startGame() {
        let self = this;
        this.gameCamera && this.gameCamera.lateUpdate2(1);

        FightDamageDisplay.getInstance.resetCount();
        this.handShankBg.active = true;
        // GameVoManager.getInstance.myUserVo.tempTopLevel = GameVoManager.getInstance.myUserVo.top_level;

        //获取数据
        let gunid = GameVoManager.getInstance.myUserVo.default_gunId;
        let gunid2 = GlobalData.inst.tiaozhandata.default_gunId;

        let battle1 = GameVoManager.getInstance.myUserVo.battle;
        let battle2 = GlobalData.inst.tiaozhandata.battle;

        let hp1 = GameVoManager.getInstance.myUserVo.baseAllHp;
        let hp2 = GlobalData.inst.tiaozhandata.baseAllHp;
        let maxhp1 = GameVoManager.getInstance.myUserVo.baseAllHp;
        let maxhp2 = GlobalData.inst.tiaozhandata.baseAllHp;
        console.log(battle1, battle2)

        let weaponInfo = Cfg.Weapon.get(gunid);
        let weaponInfo2 = Cfg.Weapon.get(gunid2);
        if (!weaponInfo) { weaponInfo = Cfg.Weapon.get(105); }
        if (!weaponInfo2) { weaponInfo2 = Cfg.Weapon.get(105); }
        // console.log("weaponInfo======;", weaponInfo)
        // console.log("weaponInfo2======;", weaponInfo2)
        let bulletNum = weaponInfo.bulletNum > weaponInfo2.bulletNum ?
            weaponInfo2.bulletNum : weaponInfo.bulletNum;
        bulletNum = Math.min(bulletNum, 10);

        //初始化角色
        this.roles.self.init(0, this.mainRole, 0);
        this.roles.self.setGunInfo(gunid);
        this.roles.self.getGunInfo().initSkillInfo();
        this.roles.self.isCanReliVe = true;
        this.roles.self.resetHp(maxhp1, false);
        this.roles.self.setCurHp(hp1);
        this.roles.self.Pos = cc.v2(0, -300);

        this.roles.enemy.init(0, this.enemyRole, 0);
        this.roles.enemy.setGunInfo(gunid2);
        this.roles.enemy.getGunInfo().initSkillInfo();
        this.roles.enemy.isCanReliVe = true;
        this.roles.enemy.resetHp(maxhp2, false);
        this.roles.enemy.setCurHp(hp2);
        this.roles.enemy.Pos = cc.v2(0, 300);
        let timer;

        //游戏结束
        let gameend = () => {
            clearInterval(timer);
            this.roles.self = null;
            this.roles.enemy = null;

            let battle = 0;
            let coin = 0;
            if (battle1 >= battle2) {
                console.log("我获胜");
                battle = Math.floor(GlobalData.inst.tiaozhandata.battle * 0.01);
                coin = 5000;
                if (GlobalData.inst.tiaozhandata.type == "ruzhu") {
                    this.showRuzhu();
                }else if(GlobalData.inst.tiaozhandata.type == "prizePool"){
                    this.showPrize();
                } 
                else {
                    AlertManager.showNormalTips("胜利");
                }
            } else {
                console.log("对方获胜");
                AlertManager.showNormalTips("失败");
                battle = -(Math.floor(GameVoManager.getInstance.getBattle() * 0.01));
                coin = -5000;
                if (GlobalData.inst.tiaozhandata.type == "ruzhu") {
                    this.scheduleOnce(() => {
                        this.onClose();
                    }, 1.5)
                }
                if (GlobalData.inst.tiaozhandata.type == "prizePool") {
                    this.scheduleOnce(() => {
                        this.onClose();
                    }, 1.5)
                }
            }

            if (GlobalData.inst.tiaozhandata.type == "rank") { //排行榜挑战成功后显示奖励
                NetAdapter.setDiffUserInfoDev({
                    touid : GlobalData.inst.tiaozhandata.uid,
                }).then(res => { 
                    this.scheduleOnce(() => {
                        this.rewardPanel.active = true;
                        this.coinLabel.string = res.info.diffcoin.toString();
                        this.battleLabel.string = res.info.diffbattle.toString();
                    }, 1.5)
                 })
                // NetAdapter.setDiffUserInfo({
                //     touid: GlobalData.inst.tiaozhandata.uid,
                //     changecoin: -coin,
                //     changebattle: -battle
                // }).then(res => { })
                // NetAdapter.setDiffUserInfo({
                //     touid: GlobalData.inst.uid,
                //     changecoin: coin,
                //     changebattle: battle
                // }).then(res => { })

                // this.scheduleOnce(() => {
                //     this.rewardPanel.active = true;
                //     this.coinLabel.string = coin.toString();
                //     this.battleLabel.string = battle.toString();
                // }, 1.5)
            } else {

            }

        }

        //开始战斗
        let idx = 0;
        timer = setInterval(() => {
            idx++;
            if (idx == bulletNum) {
                if (battle1 >= battle2) {
                    this.roles.enemy.setCurHp(0);
                } else {
                    this.roles.self.setCurHp(0);
                }
                gameend();
                return;
            }
            this.roles.self.onFire2(false, cc.v2(0, 100));
            this.roles.enemy.onFire2(false, cc.v2(0, -100));
            // hp1 -= (maxhp2 / bulletNum);
            // hp2 -= (maxhp1 / bulletNum);
            hp1 -= ((maxhp1 / bulletNum) * (battle2 / battle1));
            hp2 -= ((maxhp2 / bulletNum) * (battle1 / battle2));
            // hp1 -= (battle2 / bulletNum);
            // hp2 -= (battle1 / bulletNum);
            this.roles.self.setCurHp(hp1);
            this.roles.enemy.setCurHp(hp2);
            if (hp1 <= 0 || hp2 <= 0) {
                if (hp1 <= 0) {
                    this.roles.self.setCurHp(0);
                }
                if (hp2 <= 0) {
                    this.roles.enemy.setCurHp(0);
                }
                gameend();
            }
        }, 500)
    }
    showPrize(){
        if (GlobalData.inst.tiaozhandata.type == "prizePool"){
            let senddata = {
                to_uid: GlobalData.inst.tiaozhandata.uid
            }
            AlertManager.showNormalTips("胜利");
            NetAdapter.addPrizePool(senddata)
            .then((res: any) => {
                let msg = res.msg;
                // if (res.code == 0) {
                    msg = msg || "入驻成功";
                // }
                AlertManager.showNormalTips(msg);
                this.scheduleOnce(() => {
                    this.onClose();
                }, 1.5)
            }).catch((err) => {
                console.log("奖池错误",err);
                this.scheduleOnce(() => {
                    this.onClose();
                }, 1.5)
            })
        }
    }
    showRuzhu() {
        if (GlobalData.inst.tiaozhandata.type == "ruzhu") {

            let senddata = {
                island_id: GlobalData.inst.tiaozhandata.island_id,
                to_uid: GlobalData.inst.tiaozhandata.uid
            }
            AlertManager.showAlert(AlertType.SELECT, {
                reasonDesc: `挑战成功`,
                wayDesc: "是否入驻此岛屿",
                confirmText: "是",
                cancelText: "否",
                cancel: () => {
                    this.onClose();
                },
                confirm: () => {
                    NetAdapter.addMoveIntoUser(senddata).then((res: any) => {
                        console.log(senddata.island_id + "入驻信息", res);
                        let msg = res.msg;
                        // if (res.code == 0) {
                            msg = msg || "入驻成功";
                        // }
                        AlertManager.showNormalTips(msg);
                        this.scheduleOnce(() => {
                            this.onClose();
                        }, 1.5)
                    }).catch((err) => {
                        this.scheduleOnce(() => {
                            this.onClose();
                        }, 1.5)
                    })
                },
            });
            this.scheduleOnce(() => {
                AlertManager.showNormalTips("胜利");
            }, 1)
        }
    }

    // update (dt) {}

    lateUpdate(dt) {
    }

    onClose() {
        cc.director.loadScene(Const.GAME_SCENENAME, () => {
            // HD_MODULE.getNet().postGameEvent({ event_name: 'loadend', counter: 1 });
            Notifier.send(ListenID.Log_Event, { event_name: "loadend" });
            GameVoManager.getInstance.myUserVo.loadState = 2;
        });
    }


}
